package com.ruoyi.framework.websocket;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.concurrent.Semaphore;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/websocket/message/{userId}")
public class WebSocketServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
    public static int socketMaxOnlineCount = 100;
    private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);
    private static final Gson gson = new Gson();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws Exception {
        boolean semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag) {
            LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
            session.close();
        } else {
            WebSocketUsers.put(userId, session);
            LOGGER.info("\n 建立连接 - userId: {}, session: {}", userId, session);
            WebSocketUsers.sendMessageToUserByText(session, "连接成功");
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(@PathParam("userId") String userId, Session session) {
        LOGGER.info("\n 关闭连接 - userId: {}, session: {}", userId, session);
        WebSocketUsers.remove(userId);
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(@PathParam("userId") String userId, Session session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        LOGGER.error("\n 连接异常 - userId: {}, 异常信息 - {}", userId, exception);
        WebSocketUsers.remove(userId);
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        LOGGER.info("\n 接收到消息: {}", message);
        try {
            // 使用 Gson 解析消息
            JsonObject jsonMessage = gson.fromJson(message, JsonObject.class);
            String targetUserId = jsonMessage.get("to").getAsString();
            String msgContent = jsonMessage.get("message").getAsString();

            Session targetSession = WebSocketUsers.get(targetUserId);
            if (targetSession != null && targetSession.isOpen()) {
                WebSocketUsers.sendMessageToUserByText(targetSession, msgContent);
            } else {
                WebSocketUsers.sendMessageToUserByText(session, "目标用户不在线");
            }
        } catch (Exception e) {
            LOGGER.error("\n 消息处理异常", e);
        }
    }
}
